package com.store.service.impl;

import com.store.dto.response.DashboardResponse;
import com.store.entity.Order;
import com.store.entity.Product;
import com.store.entity.User;
import com.store.service.DashboardService;
import com.store.service.OrderService;
import com.store.service.ProductService;
import com.store.service.UserService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
public class DashboardServiceImpl implements DashboardService {
    
    private final UserService userService;
    private final OrderService orderService;
    private final ProductService productService;
    
    @Override
    public DashboardResponse getDashboardData() {
        DashboardResponse response = new DashboardResponse();
        
        // 获取当前用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        if (authentication == null || !authentication.isAuthenticated()) {
            throw new RuntimeException("未登录或登录已失效");
        }
        
        User user = (User) authentication.getPrincipal();
        if (user == null) {
            throw new RuntimeException("用户不存在");
        }
        
        response.setUsername(user.getUsername());
        response.setRole(user.getRole());
        response.setLastLoginTime(user.getLastLoginTime());
        
        // 获取待发货订单数
        response.setPendingOrders(orderService.countByStatus("PENDING"));
        
        // 获取今日销售额
        response.setTodaySales(orderService.getTodaySales());
        
        // 获取销售额最高的商品
        Product topProduct = productService.getTopSalesProduct();
        if (topProduct != null) {
            DashboardResponse.ProductInfo productInfo = new DashboardResponse.ProductInfo();
            productInfo.setId(topProduct.getProductId());
            productInfo.setName(topProduct.getProductName());
            productInfo.setSales(productService.getProductSales(topProduct.getProductId()));
            response.setTopProduct(productInfo);
        }
        
        return response;
    }
    
    @Override
    public Map<String, Object> getSalesTrend() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取近7个月的销售数据
        LocalDate now = LocalDate.now();
        String[] months = new String[7];
        BigDecimal[] values = new BigDecimal[7];
        
        for (int i = 6; i >= 0; i--) {
            LocalDate date = now.minusMonths(i);
            months[6 - i] = date.format(DateTimeFormatter.ofPattern("yyyy-MM"));
            values[6 - i] = orderService.getMonthlySales(date);
        }
        
        result.put("months", months);
        result.put("values", values);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getCategorySales() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取近3年的销售数据
        LocalDate now = LocalDate.now();
        String[] years = new String[3];
        Map<String, BigDecimal[]> categoryValues = new HashMap<>();
        
        for (int i = 2; i >= 0; i--) {
            LocalDate date = now.minusYears(i);
            years[2 - i] = String.valueOf(date.getYear());
        }
        
        // 获取所有分类的销售数据
        List<String> categories = productService.getAllCategories();
        for (String category : categories) {
            BigDecimal[] values = new BigDecimal[3];
            for (int i = 2; i >= 0; i--) {
                LocalDate date = now.minusYears(i);
                values[2 - i] = orderService.getMonthlySales(date); // 使用月度销售额代替分类销售额
            }
            categoryValues.put(category, values);
        }
        
        result.put("years", years);
        result.put("values", categoryValues);
        
        return result;
    }
    
    @Override
    public Map<String, Object> getCategoryPercentage() {
        Map<String, Object> result = new HashMap<>();
        
        // 获取所有分类的销售占比
        List<String> categories = productService.getAllCategories();
        String[] categoryNames = categories.toArray(new String[0]);
        BigDecimal[] percentages = new BigDecimal[categories.size()];
        
        BigDecimal totalSales = orderService.getTotalSales();
        if (totalSales.compareTo(BigDecimal.ZERO) == 0) {
            // 如果没有销售数据，平均分配
            BigDecimal equalPercentage = new BigDecimal("100").divide(new BigDecimal(categories.size()), 4, BigDecimal.ROUND_HALF_UP);
            Arrays.fill(percentages, equalPercentage);
        } else {
            // 如果有销售数据，使用月度销售额计算占比
            for (int i = 0; i < categories.size(); i++) {
                percentages[i] = orderService.getMonthlySales(LocalDate.now())
                        .divide(totalSales, 4, BigDecimal.ROUND_HALF_UP)
                        .multiply(new BigDecimal("100"));
            }
        }
        
        result.put("categories", categoryNames);
        result.put("percentages", percentages);
        
        return result;
    }
} 